package com.gs.douban.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.log4j.Logger;

import com.gs.douban.model.Song;
import com.mpatric.mp3agic.ID3v1;
import com.mpatric.mp3agic.ID3v1Tag;
import com.mpatric.mp3agic.InvalidDataException;
import com.mpatric.mp3agic.Mp3File;
import com.mpatric.mp3agic.NotSupportedException;
import com.mpatric.mp3agic.UnsupportedTagException;

public class Mp3Maker {
	private static Logger LOG = Logger.getLogger(Mp3Maker.class);
	
	public static final synchronized void make(Song song,String path) throws NotSupportedException{
		final String filename = (song.getTitle() + "-" +song.getArtist()).replaceAll("\\\\", " ").replaceAll("/", " ") + ".mp3";
		File file = new File(path+"/"+filename);
		if(file.exists()){
			LOG.info(filename + " 已经下载过,跳过");
			return;
		}else{
			LOG.info("正在下载  " + filename);
		}
	        int byteread = 0;
	        URL url = null;
			try {
				url = new URL(song.url);
			} catch (MalformedURLException e1) {
				LOG.error(e1.getMessage());
			}
	        try {
	            URLConnection conn = url.openConnection();
	            InputStream inStream = conn.getInputStream();
	            FileOutputStream fs = new FileOutputStream(file);
	            byte[] buffer = new byte[1204];
	            while ((byteread = inStream.read(buffer)) != -1) {
	                fs.write(buffer, 0, byteread);
	            }
	            fs.close();
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        /*try {
				Mp3File mp3file = new Mp3File(file.getAbsolutePath());
				ID3v1 id3v1Tag;
				if (mp3file.hasId3v1Tag()) {
				  id3v1Tag =  mp3file.getId3v1Tag();
				} else {
				  // mp3 does not have an ID3v1 tag, let's create one..
				  id3v1Tag = new ID3v1Tag();
				  mp3file.setId3v1Tag(id3v1Tag);
				}
				id3v1Tag.setArtist(new String(song.artist.getBytes("utf8"),"gb2312"));
				id3v1Tag.setTitle(new String(song.title.getBytes("utf8"),"gb2312"));
				id3v1Tag.setAlbum(new String(song.albumtitle.getBytes("utf8"),"gb2312"));
				LOG.info(new String(song.artist.getBytes("iso8859-1"),"utf8"));
				id3v1Tag.setYear(song.public_time);
				mp3file.setId3v1Tag(id3v1Tag);
				mp3file.save(path+"/" + filename);
				file.delete();
			} catch (UnsupportedTagException e) {
				LOG.error(e.getMessage());
				e.printStackTrace();
			} catch (InvalidDataException e) {
				LOG.error(e.getMessage());
				e.printStackTrace();
			} catch (IOException e) {
				LOG.error(e.getMessage());
				e.printStackTrace();
			} */
	}

}
